package com.it.sendmail.Utils;

import com.it.sendmail.Dao.MailBean;
import com.it.sendmail.Dao.RespBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCodeutils {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    MailBean mailBean;

    public static final String CODE_PREFIX = "codenumber";

    public  RespBean  codeReturn(){
        //先去reids找有没有此key：判断是否拿取过验证码
        String redisCode = stringRedisTemplate.opsForValue().get(CODE_PREFIX + mailBean.getRecipient());
        if(!StringUtils.isEmpty(redisCode)) {     //防止同一个人在60s内再次发送验证码
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60 * 1000) {
                return RespBean.error("获取频率太高");
            }
        }
        //redis存储，key-邮箱 ,value-code
        String code = UUID.randomUUID().toString().substring(0,5)+"_"+System.currentTimeMillis();
        //验证码加盐
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(code);
        //redis缓存10min的验证码
        stringRedisTemplate.opsForValue().set(CODE_PREFIX+mailBean.getRecipient() ,code,10, TimeUnit.MINUTES);
        return RespBean.success("成功",code);
    }


}
